#include "admin_view.h"
#include "ui_admin_view.h"
#include <QSqlError>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QDebug>
#include <QHeaderView>
#include <QTextCodec>

// 数据管理实现
GeneralDataManagementWidget::GeneralDataManagementWidget(const QString& tableName, const QStringList& columnHeaders, QWidget *parent)
    : QWidget(parent), tableName(tableName), columnHeaders(columnHeaders) {
    // 初始化UI
    dataTable = new QTableWidget(0, columnHeaders.count(), this);
    dataTable->setHorizontalHeaderLabels(columnHeaders);
    dataTable->horizontalHeader()->setStretchLastSection(true);

    queryBtn = new QPushButton("查询", this);
    addBtn = new QPushButton("增加", this);
    deleteBtn = new QPushButton("删除", this);
    saveBtn = new QPushButton("保存", this);

    QHBoxLayout *searchLayout = new QHBoxLayout();//水平布局
    QLabel *searchLabel = new QLabel("搜索:", this);
    searchEdit = new QLineEdit(this);
    searchEdit->setPlaceholderText("输入搜索关键词");
    searchBtn = new QPushButton("搜索", this);
    resetSearchBtn = new QPushButton("重置", this);
    searchLayout->addWidget(searchLabel);
    searchLayout->addWidget(searchEdit);
    searchLayout->addWidget(searchBtn);
    searchLayout->addWidget(resetSearchBtn);

    QHBoxLayout *btnLayout = new QHBoxLayout();
    btnLayout->addWidget(queryBtn);
    btnLayout->addWidget(addBtn);
    btnLayout->addWidget(deleteBtn);
    btnLayout->addWidget(saveBtn);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(searchLayout);
    mainLayout->addLayout(btnLayout);
    mainLayout->addWidget(dataTable);
    setLayout(mainLayout);

    // 信号槽连接
    connect(queryBtn, &QPushButton::clicked, this, &GeneralDataManagementWidget::onQueryClicked);
    connect(addBtn, &QPushButton::clicked, this, &GeneralDataManagementWidget::onAddClicked);
    connect(deleteBtn, &QPushButton::clicked, this, &GeneralDataManagementWidget::onDeleteClicked);
    connect(saveBtn, &QPushButton::clicked, this, &GeneralDataManagementWidget::onSaveClicked);
    connect(searchBtn, &QPushButton::clicked, this, &GeneralDataManagementWidget::onSearchClicked);
    connect(resetSearchBtn, &QPushButton::clicked, this, &GeneralDataManagementWidget::onResetSearchClicked);
    // 初始化字段映射（QMap保证顺序）
    if (tableName == "user") {
        fieldMap.insert("ID", "id");          // 表格第0列
        fieldMap.insert("用户名", "user_name"); // 表格第1列
        fieldMap.insert("账号", "account");    // 表格第2列
        fieldMap.insert("账号密码", "password");    // 表格第3列
    } else if (tableName == "gear") {
        fieldMap.insert("ID", "gear_id");     // 表格第0列
        fieldMap.insert("名称", "gear_name"); // 表格第1列
        fieldMap.insert("装备价值", "gear_value"); // 表格第2列
        fieldMap.insert("装备槽ID", "gear_slot_id"); // 表格第3列
    } else if (tableName == "monster") {
        fieldMap.insert("怪兽ID", "monster_id");   // 表格第0列
        fieldMap.insert("怪兽名称", "monster_name"); // 表格第1列
        fieldMap.insert("怪物价值", "monster_value");  // 表格第2列
    }

    connectDatabase();
    QMap<QString, QVariant> whereConditions;
    queryData1(whereConditions);
}

// 连接数据库（使用工具类）
bool GeneralDataManagementWidget::connectDatabase() {
    // 打开数据库
    if (!sqlOp.open("./pro.db", tableName + "Connection")) {
        QMessageBox::critical(this, "数据库错误", "无法打开数据库: " + sqlOp.lastError());
        return false;
    }
    // 检查表是否存在，不存在则创建（用QMap保证字段顺序）
    if (!sqlOp.isExistTable(tableName)) {
        QMap<QString, QString> fields; // 有序容器，保证建表字段顺序
        QList<QString> pks;
        if (tableName == "gear") {
            fields.insert("gear_id", "INTEGER");
            fields.insert("gear_name", "TEXT");
            fields.insert("gear_value", "INTEGER");
            fields.insert("gear_slot_id", "INTEGER");
            pks = {"gear_id"};
        } else if (tableName == "monster") {
            fields.insert("monster_id", "INTEGER");
            fields.insert("monster_name", "TEXT");
            fields.insert("monster_value", "INTEGER");
            pks = {"monster_id"};
        } else if (tableName == "user") {
            fields.insert("id", "INTEGER");
            fields.insert("user_name", "TEXT");
            fields.insert("account", "TEXT");
            fields.insert("password", "TEXT");
            pks = {"id"};
        }
        if (!sqlOp.createTable1(tableName, fields, pks)) {
            QMessageBox::critical(this, "数据库错误", "创建表失败: " + sqlOp.lastError());
            return false;
        }
    }
    return true;
}

// 查询数据（使用工具类selectData1）
void GeneralDataManagementWidget::queryData1(const QMap<QString, QVariant> &whereConditions) {
    QList<QVariantList> data;
    // 调用 sqlOp.selectData1，传递 whereConditions 参数
    if (!sqlOp.selectData1(tableName, fieldMap.values(), whereConditions, data)) {
        QMessageBox::warning(this, "查询错误", sqlOp.lastError());
        return;
    }

    // 填充表格
    dataTable->setRowCount(0);
    int row = 0;
    for (const auto &rowData : data) {
        dataTable->insertRow(row);
        for (int col = 0; col < columnHeaders.count(); ++col) {
            dataTable->setItem(row, col, new QTableWidgetItem(rowData[col].toString()));
        }
        row++;
    }
}


// 修改 onQueryClicked 函数，传递空的 QMap 作为查询条件（表示无查询条件，查询所有数据）
// 查询按钮
void GeneralDataManagementWidget::onQueryClicked() {
    QMap<QString, QVariant> whereConditions;
    queryData1(whereConditions);
}

// 增加行
void GeneralDataManagementWidget::onAddClicked() {
    int row = dataTable->rowCount();
    dataTable->insertRow(row);
    for (int col = 0; col < columnHeaders.count(); col++) {
        dataTable->setItem(row, col, new QTableWidgetItem(""));
    }
    qDebug()<<row<<"";
}

// 删除行
void GeneralDataManagementWidget::onDeleteClicked() {
    int currentRow = dataTable->currentRow();
    if (currentRow >= 0) {
        dataTable->removeRow(currentRow);
    } else {
        QMessageBox::warning(this, "提示", "请先选择要删除的行");
    }
}

// 保存数据（使用工具类事务+删除+插入）
void GeneralDataManagementWidget::onSaveClicked() {
    if (!sqlOp.hasTransactions()) {
        QMessageBox::critical(this, "错误", "数据库不支持事务");
        return;
    }

    // 开启事务
    if (!sqlOp.transaction()) {
        QMessageBox::critical(this, "事务错误", "无法开启事务: " + sqlOp.lastError());
        return;
    }

    // 清空表数据
    if (!sqlOp.deleteData(tableName, {})) { // 无条件删除所有数据
        sqlOp.rollback();
        QMessageBox::critical(this, "保存错误", "清空表失败: " + sqlOp.lastError());
        return;
    }

    // 插入表格数据
    QList<QVariantList> rowsData;
    for (int row = 0; row < dataTable->rowCount(); ++row) {
        // 检查关键字段
        QTableWidgetItem *nameItem = dataTable->item(row, 1);
        if (!nameItem || nameItem->text().isEmpty()) {
            sqlOp.rollback();
            QMessageBox::warning(this, "保存错误", QString("%1不能为空").arg(columnHeaders[1]));
            return;
        }

        // 收集行数据
        QVariantList rowData;
        for (int col = 0; col < columnHeaders.count(); ++col) {
            QTableWidgetItem *item = dataTable->item(row, col);
            QString value = item ? item->text() : "";
            rowData.append(value);
        }
        rowsData.append(rowData);
    }

    // 批量插入
    if (!sqlOp.insertRowsData(tableName, fieldMap.values(), rowsData)) {
        sqlOp.rollback();
        QMessageBox::critical(this, "保存错误", "插入数据失败: " + sqlOp.lastError());
        return;
    }

    // 提交事务
    if (sqlOp.commit()) {
        QMessageBox::information(this, "成功", "数据保存成功");
    } else {
        sqlOp.rollback();
        QMessageBox::critical(this, "保存错误", "事务提交失败: " + sqlOp.lastError());
    }
}

// 搜索功能（使用工具类selectDataBySql）
void GeneralDataManagementWidget::onSearchClicked() {
    QString keyword = searchEdit->text().trimmed();
    if (keyword.isEmpty()) {
        QMessageBox::information(this, "提示", "请输入搜索关键词");
        return;
    }

    QList<QVariantList> data;
    QString sql = getSearchSql(keyword);
    if (!sqlOp.selectDataBySql(sql, fieldMap.values(), data)) {
        QMessageBox::warning(this, "查询错误", sqlOp.lastError());
        return;
    }

    // 显示结果
    dataTable->setRowCount(0);
    int row = 0;
    for (const auto &rowData : data) {
        dataTable->insertRow(row);
        for (int col = 0; col < columnHeaders.count(); ++col) {
            dataTable->setItem(row, col, new QTableWidgetItem(rowData[col].toString()));
        }
        row++;
    }

    if (row == 0) {
        QMessageBox::information(this, "结果", "未找到匹配的记录");
    }
}

// 重置搜索
void GeneralDataManagementWidget::onResetSearchClicked() {
    searchEdit->clear();
    QMap<QString, QVariant> whereConditions;
    queryData1(whereConditions);
}

// 默认搜索SQL（显式指定字段顺序）
QString GeneralDataManagementWidget::getSearchSql(const QString& keyword) {
    QString fields = fieldMap.values().join(", "); // 按fieldMap顺序拼接字段
    if (keyword.isEmpty()) {
        return QString("SELECT %1 FROM %2").arg(fields, tableName);
    }

    // 生成条件
    QString conditions;
    for (const QString& field : fieldMap.values()) {
        if (!conditions.isEmpty()) {
            conditions += " OR ";
        }
        conditions += QString("%1 LIKE '%%2%'").arg(field, keyword);
    }

    return QString("SELECT %1 FROM %2 WHERE %3").arg(fields, tableName, conditions);
}

// 密码重置窗口实现
ResetPasswordWidget::ResetPasswordWidget(QWidget *parent) : QWidget(parent) {

    QLabel *label = new QLabel("请输入账号:", this);
    accountEdit = new QLineEdit(this);
    resetBtn = new QPushButton("重置密码为123456", this);

    searchResultList = new QListWidget(this);
    searchResultList->setVisible(false);
    searchResultList->setStyleSheet("border: 1px solid #ccc; border-radius: 3px;");
    searchResultList->setMaximumHeight(150);

    connect(accountEdit, &QLineEdit::textChanged, this, &ResetPasswordWidget::onTextChanged);
    connect(resetBtn, &QPushButton::clicked, this, &ResetPasswordWidget::onResetClicked);

    QHBoxLayout *layout = new QHBoxLayout();
    layout->addWidget(label);
    layout->addWidget(accountEdit);
    layout->addWidget(resetBtn);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(layout);
    mainLayout->addWidget(searchResultList);
    mainLayout->addStretch();

    setLayout(mainLayout);

    connectDatabase();
}

// 连接数据库
bool ResetPasswordWidget::connectDatabase() {
    if (!sqlOp.open("./pro.db", "resetConnection")) {
        QMessageBox::critical(this, "数据库错误", "无法打开数据库: " + sqlOp.lastError());
        return false;
    }
    return true;
}

// 重置密码（使用工具类updateData）
void ResetPasswordWidget::onResetClicked() {
    QString account = accountEdit->text().trimmed();
    if (account.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入账号");
        return;
    }

    QHash<QString, QVariant> updateData;
    updateData["password"] = "123456";

    QHash<QString, QVariant> conditions;
    conditions["account"] = account;

    if (sqlOp.updateData("user", updateData, conditions)) {
        if (sqlOp.size() > 0) {
            QMessageBox::information(this, "成功", "密码已重置为123456");
            accountEdit->clear();
        } else {
            QMessageBox::warning(this, "提示", "未找到该账号");
        }
    } else {
        QMessageBox::critical(this, "错误", sqlOp.lastError());
    }
}

// 账号输入变化（使用工具类selectDataBySql）
void ResetPasswordWidget::onTextChanged(const QString &text) {
    if (text.isEmpty()) {
        searchResultList->clear();
        searchResultList->setVisible(false);
        return;
    }

    QList<QVariantList> data;
    QString sql = QString("SELECT account, user_name FROM user WHERE account LIKE '%%1%'").arg(text);
    if (!sqlOp.selectDataBySql(sql, {"account", "user_name"}, data)) {
        qDebug() << "搜索失败:" << sqlOp.lastError();
        searchResultList->setVisible(false);
        return;
    }

    searchResultList->clear();
    int count = 0;
    for (const auto &row : data) {
        QString account = row[0].toString();
        QString userName = row[1].toString();
        new QListWidgetItem(QString("账号:%1  |  用户名:%2").arg(account).arg(userName), searchResultList);
        count++;
    }
    searchResultList->setVisible(count > 0);
}

// 主窗口实现
AdminView::AdminView(QWidget *parent) : QMainWindow(parent), ui(new Ui::admin_view) {
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    ui->setupUi(this);
    setWindowTitle("管理员系统");
    resize(1000, 600);

    centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    mainLayout = new QHBoxLayout(centralWidget);

    QGroupBox *leftGroupBox = ui->_;
    leftGroupBox->setTitle("功能菜单");
    leftGroupBox->setMinimumWidth(120);
    leftGroupBox->setMaximumWidth(150);
    mainLayout->addWidget(leftGroupBox);

    mdiArea = new QMdiArea(this);
    mdiArea->setViewMode(QMdiArea::TabbedView);
    mainLayout->addWidget(mdiArea, 1);

    // 初始化子窗口
    userWidget = new UserManagementWidget();
    equipmentWidget = new EquipmentManagementWidget();
    monsterWidget = new MonsterManagementWidget();
    resetPwdWidget = new ResetPasswordWidget();

    userWindow = mdiArea->addSubWindow(userWidget);
    userWindow->setWindowTitle("用户管理");

    equipmentWindow = mdiArea->addSubWindow(equipmentWidget);
    equipmentWindow->setWindowTitle("装备管理");

    monsterWindow = mdiArea->addSubWindow(monsterWidget);
    monsterWindow->setWindowTitle("怪物管理");

    resetPwdWindow = mdiArea->addSubWindow(resetPwdWidget);
    resetPwdWindow->setWindowTitle("重置密码");

    // 连接按钮信号槽
    connect(ui->userManagementBtn, &QPushButton::clicked, this, &AdminView::onUserManagementClicked);
    connect(ui->equipmentBtn, &QPushButton::clicked, this, &AdminView::onEquipmentManagementClicked);
    connect(ui->monsterBtn, &QPushButton::clicked, this, &AdminView::onMonsterManagementClicked);
    connect(ui->resetPwdBtn, &QPushButton::clicked, this, &AdminView::onResetPasswordClicked);
    connect(ui->exitBtn, &QPushButton::clicked, this, &AdminView::onExitClicked);
    onUserManagementClicked();
}

AdminView::~AdminView() {
    delete ui;
}

// 窗口切换
void AdminView::onUserManagementClicked() {
    foreach (QMdiSubWindow *subWindow, mdiArea->subWindowList()) {
        subWindow->hide();
    }
    userWindow->showMaximized();
}

void AdminView::onEquipmentManagementClicked() {
    foreach (QMdiSubWindow *subWindow, mdiArea->subWindowList()) {
        subWindow->hide();
    }
    equipmentWindow->showMaximized();
}

void AdminView::onMonsterManagementClicked() {
    foreach (QMdiSubWindow *subWindow, mdiArea->subWindowList()) {
        subWindow->hide();
    }
    monsterWindow->showMaximized();
}

void AdminView::onResetPasswordClicked() {
    foreach (QMdiSubWindow *subWindow, mdiArea->subWindowList()) {
        subWindow->hide();
    }
    resetPwdWindow->showMaximized();
}

void AdminView::showAdminWindow(QWidget *parent) {
    AdminView *adminWindow = new AdminView(parent);
    adminWindow->setAttribute(Qt::WA_DeleteOnClose);
    adminWindow->show();

}

void AdminView::onExitClicked() {
 emit signalClose();//发送信号通知窗口mian_widget显示
 this->close();//关闭admin窗口
}

